package com.hexiang.web;

import com.hexiang.domain.QueryParam;
import com.hexiang.entity.User;
import com.hexiang.service.UserServiceImpl;
import com.hexiang.tools.SensitiveInfoUtils;
import com.hexiang.web.request.QueryParamRequest;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@RestController
@Validated
public class UserController {
    @Resource
    private UserServiceImpl userService;

    @GetMapping("/selectAll")
    public List<User> selectAll() {
        return userService.selectAll();
    }

    @GetMapping("/selectAllWithDesensitization")
    public List<User> selectAllWithDesensitization() {
        List<User> userList = userService.selectAll();
        if (CollectionUtils.isNotEmpty(userList)) {
            userList.forEach(user -> {
                        user.setPwd(SensitiveInfoUtils.cnapsCode(user.getPwd()));
                        user.setPhone(SensitiveInfoUtils.mobilePhone(user.getPhone()));
                    }
            );
        }
        return userList;
    }

    @PostMapping("/saveUser")
    public User saveUser(@RequestBody @Validated User user) {
        return userService.save(user);
    }

    @PostMapping("/updateUser")
    public User updateUser(@RequestBody @Validated User user) {
        return userService.update(user);
    }

    @PostMapping("/handleHistoryData")
    public String handleHistoryData(@RequestBody @Validated QueryParamRequest queryParamRequest) {
        userService.handleHistoryData(QueryParam.builder().startCreateTime(LocalDateTime.parse(queryParamRequest.getStartCreateTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))).endCreateTime(LocalDateTime.parse(queryParamRequest.getEndCreateTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))).build());
        return "ok";
    }
}
